<template>
	<div class="player" v-show="playlist.length > 0">
		<!-- 全屏播放器 -->
		<transition name="normal">
			<div class="normal-player" v-show="fullScreen">
        <!-- 背景图 -->
				<div class="normal-bg">
					<img :src="currentSong.image" alt="">
				</div>
				<div class="header">
					<img src="@/assets/img/icon-down.png" alt="收回" @click="toDown">
					<h1 v-html="currentSong.name"></h1>
				</div>
				<h1 class="title-singer" v-html="currentSong.singer"></h1>
        <!-- 音量控制 -->
        <!-- <div class="volume">
          <img src="@/assets/img/icon-soundsize.png" alt="">
          <ProgressBar style="overflow:hidden" class="volume-control" :percent="volPercent" @percentChange="volPercentChange"></ProgressBar>
        </div> -->
				<!-- 旋转大头像 -->
				<div class="middle" @touchstart.prevent="middleTouchStart" @touchmove.prevent="middleTouchMove" @touchend="middleTouchEnd">
					<img :class="playImg" :src="currentSong.image" alt="">
					<p :class="playImgTxt" class="cd-lyric">{{playingLyric}}</p>
					<Scroll class="middle-r middleTime" ref="lyricList" :data="currentLyric && currentLyric.lines">
						<div class="lyric-wrapper">
							<div v-if="currentLyric">
								<p ref="lyricLine" class="text" :class="{'current': currentLineNum ===index}" v-for="(line, index) in currentLyric.lines" :key="index">{{line.txt}}</p>
							</div>
						</div>
					</Scroll>
				</div>
				<!-- 歌词旋转图像轮播 -->
				<div class="dot-wrapper">
					<span class="dot" :class="{'active':currentShow==='cd'}"></span>
					<span class="dot" :class="{'active':currentShow==='lyric'}"></span>
				</div>
				<!-- 播放进度条 -->
				<div class="time-box">
					<div class="time">
						<span class="time-l">{{ format(currentTime) }}</span>
						<ProgressBar style="overflow:hidden" :percent="percent" @percentChange="percentChange"></ProgressBar>
						<span class="time-r">{{ format(currentSong.duration) }}</span>
					</div>
				</div>
				<!-- 控制按钮栏 -->
				<div class="bottom-button-box">
					<span @click="changeMode">
						<img v-if="mode === 2" src="@/assets/img/icon-random.png" alt="">
						<img v-if="mode === 0" src="@/assets/img/icon-sequence.png" alt="">
						<img v-if="mode === 1" src="@/assets/img/icon-loop.png" alt="">
					</span>
					<span @click="prev"><img src="@/assets/img/icon-prev.png" alt=""></span>
					<span @click="togglePlaying">
						<img v-if="playing" id="playButton" src="@/assets/img/icon-play.png" alt="">
						<img v-if="!playing" id="playButton" src="@/assets/img/icon-stop.png" alt="">
					</span>
					<span @click="next"><img src="@/assets/img/icon-next.png" alt=""></span>
					<span @click="toggleFavoriteList(currentSong)">
						<img v-if="getFavoriteListCollect(currentSong)" src="@/assets/img/icon-collection.png" alt="收藏">
						<img v-else src="@/assets/img/icon-collections.png" alt="收藏">
					</span>
				</div>
				<!-- 音乐播放器 -->
				<audio ref="audio" @canplay="audioReady" @error="audioError"
               @timeupdate="timeUpdate" @ended="songEnd"></audio>
			</div>
		</transition>
		<!-- 收回的迷你播放器 -->
    <div class="mini-player" v-show="!fullScreen" @click="toUp">
      <div class="mini-player-con">
        <img :class="playing? 'playSrart' : 'playStorp'" :src="currentSong.image" alt="">
        <p>
          <span class="mini-title" v-html="currentSong.name"></span>
          <span class="mini-name" v-html="currentSong.singer"></span>
        </p>
        <div class="playButton-box">
          <span @click.stop="togglePlaying" class="playButton">
            <img v-if="playing" src="@/assets/img/icon-play.png" alt="">
            <img v-if="!playing" src="@/assets/img/icon-stop.png" alt="">
          </span>
          <span @click.stop="next"><img src="@/assets/img/icon-next.png" alt=""></span>
          <span class="playList" @click.stop="playListClick">
            <img src="@/assets/img/icon-musiclist.png" alt="">
          </span>
        </div>
      </div>
    </div>
    <!-- 查看播放歌曲列表 -->
    <playList ref="playList"></playList>
	</div>
</template>

<script>
import { mapGetters, mapMutations, mapActions } from 'vuex'
import { songUrl } from 'assets/js/song'
import { shuffle } from 'assets/js/util'
import { getVkey, getLyric } from 'api/song'
import { ERR_OK } from 'api/config'
import ProgressBar from 'base/progressbar/ProgressBar'
import playList from 'components/playList/playList'
import { playMode } from 'assets/js/config'
import { Base64 } from 'js-base64'
import Lyric from 'lyric-parser'
import Scroll from 'base/scroll/Scroll'
export default {
	components: {
		Scroll,
		ProgressBar,
		playList
	},
	computed: {
    ...mapGetters([
      "fullScreen",
      "playlist",
      "currentSong",
      "vkey",
      "playing",
      "currentIndex",
      "mode",
      "sequenceList",
      "favoriteList"
    ]),
    percent() {
      return this.currentTime / this.currentSong.duration
    },
    playImg() {
      let class1 = this.playing ? "playSrart" : "playStorp"
      let class2 = this.currentShow === "lyric" ? "playImg" : ""
      return `${class1} ${class2}`
    },
    playImgTxt() {
      let class2 = this.currentShow === "lyric" ? "playImg" : ""
      return `${class2}`
    },
    volPercent() {
      return this.volumes
    }
	},
	data() {
    return {
      // volumes: 0,
      songUrlData: '',
      vkeyData: '',
      songReadey: false, // 能否跳转下一曲
      currentTime: '',
      currentLyric: null, // 封装后的歌词对象
      currentShow: 'cd', // 轮播图底部导航
      currentLineNum: 0, // 当前下显示歌词行数
      playingLyric: '' // 当前cd页显示歌词
    }
	},
	created() {
    this.touch = {}
	},
	methods: {
    /* // 音量变化调节测试
    volPercentChange(volPercent){
      this.$refs.audio.volume = volPercent > 1 ? (volPercent*10-1)/10:volPercent;
      // console.log(volPercent)
    }, */
    // 收藏显示
    getFavoriteListCollect(song) {
      if (this.isFavoriteList(song)) {
        return false
      } else {
        return true
      }
    },
    // 点击收藏
    toggleFavoriteList(song) {
      if (this.isFavoriteList(song)) {
        this.deleteFavoriteList(song)
      } else {
        this.saveFavoriteList(song)
      }
    },
    // 判断当前播放歌曲是否收藏
    isFavoriteList(song) {
      const index = this.favoriteList.findIndex(item => {
        return item.id === song.id
      });
      return index > -1
    },
    /* 点击播放列表 */
    playListClick() {
      this.$refs.playList.show()
    },
    /* 播放按钮点击 */
    togglePlaying() {
      // 停止/播放当前歌词播放
      if (this.currentLyric) {
        this.currentLyric.togglePlay()
      }
      this.setPlayingState(!this.playing)
    },
    toDown() {
      this.setFullScreen(false)
    },
    toUp() {
      this.setFullScreen(true)
    },
    /* 上一曲，下一曲 */
    next() {
      if (!this.songReadey) {
        return
      }
      if (this.playlist.length === 1) {
        this.songLoop()
      } else {
        let index = this.currentIndex + 1
        if (index === this.playlist.length) {
          index = 0
        }
        this.setCurrentIndex(index)
        this.setPlayingState("true") // 点击下一曲后自动播放
        
      }
      this.songReadey = false
    },
    prev() {
      if (!this.songReadey) {
        return
      }
      if (this.playlist.length === 1) {
        this.songLoop()
      } else {
        let index = this.currentIndex - 1
        if (index === -1) {
          index = this.playlist.length - 1
        }
        this.setCurrentIndex(index)
        this.setPlayingState("false")
      }
      this.songReadey = false
    },
    /* 歌曲加载成功 */
    audioReady() {
      this.songReadey = true // 当前歌曲还未加载完成时禁止跳转其他歌曲
      this.savePlayHistory(this.currentSong) // 播放歌曲存入本地播放记录
    },
    audioError() {
      console.log("当前歌曲加载失败，请尝试其他歌曲")
      this.songReadey = true; // 歌曲加载失败是不会阻塞其他歌曲播放
    },
    /* 音频播放时间更新 */
    timeUpdate(e) {
      this.currentTime = e.target.currentTime
    },
    /* 歌曲进度条触摸后改变歌曲播放进度 */
    percentChange(precent) {
      const currentTime = this.currentSong.duration * precent
      this.$refs.audio.currentTime = currentTime
      // 歌词跟随进度条滚动
      if (this.currentLyric) {
        this.currentLyric.seek(currentTime * 1000)
      }
    },
    /* 封装歌曲当前播放时间 */
    format(interval) {
      interval = interval | 0
      var min = (interval / 60) | 0
      var sec = interval % 60
      if (sec.toString().length === 1) {
        sec = `0${sec}`
      }
      return `${min}:${sec}`
    },
    /* 改变播放顺序 */
    changeMode() {
      const mode = (this.mode + 1) % 3 // 取余
      this.setPlayMode(mode)
      let list = null
      if (mode === playMode.random) {
        list = shuffle(this.sequenceList)
      } else {
        list = this.sequenceList
      }
      this.resetCurrentIndex(list)
      this.setPlayList(list)
    },
    resetCurrentIndex(list) {
      let index = list.findIndex(item => {
        return item.id === this.currentSong.id
      })
      this.setCurrentIndex(index)
    },
    /* 歌曲播放完毕 */
    songEnd() {
      if (this.mode === playMode.loop) {
        this.songLoop()
      } else {
        this.next()
      }
    },
    /* 单曲循环播放调会播放初始 */
    songLoop() {
      // 单曲循环播放结束歌词回到初始位置
      if (this.currentLyric) {
        this.currentLyric.seek(0)
      }
      this.$refs.audio.currentTime = 0
      this.$refs.audio.play()
    },
    /* 重新请求key */
    _getVkey(mid) {
      var that = this
      getVkey(mid).then(res => {
        if (res.code === ERR_OK && res.data.items[0].vkey!=='') {
          let vkey = res.data.items[0].vkey
          that.setVkey(vkey); // 请求到的key添加到vuex
        } else {
          console.log("player组件 vkey请求错误")
          // that.playing = false
        }
      });
      /* 获取歌词 */
      getLyric(mid).then(res => {
        this.currentLyric = null
        if (res.code === ERR_OK) {
          let lyric = Base64.decode(res.lyric)
          this.currentLyric = new Lyric(lyric, this.handleLyric)
          if (this.playing) {
            // 如果此时正在播放则歌词也开始播放
            this.currentLyric.play()
          }
        } else {
          console.log("player组件 Lyric请求错误")
          this.currentLyric = null
          this.playingLyric = ""
          this.currentLineNum = 0
        }
      });
    },
    handleLyric({ lineNum, txt }) {
      this.currentLineNum = lineNum
      if (lineNum > 5) {
        let lineEl = this.$refs.lyricLine[lineNum - 5]
        this.$refs.lyricList.scrollToElement(lineEl, 1000)
      } else {
        this.$refs.lyricList.scrollTo(0, 0, 1000)
      }
      this.playingLyric = txt
    },
    /* 播放歌曲 */
    songPlay() {
      this.$refs.audio.src = this.songUrlData
      this.$refs.audio.crossOrigin = this.anonymous
      this.$refs.audio.play()
      // 初始化音量
      /* var vol = this.$refs.audio.volume;
      this.volumes = vol > 0 ? (vol*10 - 1)/10:0; */
      // console.log(this.volumes)
    },
    /* 旋转头像歌词左右滑动 */
    middleTouchStart(e) {
      this.touch.initiated = true
      // 用来判断是否是一次移动
      this.touch.moved = false
      const touch = e.touches[0]
      this.touch.startX = touch.pageX
      this.touch.startY = touch.pageY
    },
    middleTouchMove(e) {
      if (!this.touch.initiated) {
        return
      }
      const touch = e.touches[0]
      const deltaX = touch.pageX - this.touch.startX
      const deltaY = touch.pageY - this.touch.startY
      // 上下滑动大于左右滑动判定为上下滑动
      if (Math.abs(deltaY) > Math.abs(deltaX)) {
        return
      }
      if (!this.touch.moved) {
        this.touch.moved = true
      }
      /* 判断滑动方向 */
      if (deltaX > 0) {
        // 向右滑动//在歌词界面进行
        if (this.currentShow === "lyric") {
          this.touch.toChange = Math.abs(deltaX) > 40 ? "NO" : "OK"
        } else {
          return ""
        }
      } else {
        // 向左滑动//在CD界面进行
        if (this.currentShow === "cd") {
          this.touch.toChange = Math.abs(deltaX) > 40 ? "OK" : "NO" // 如果滑动距离大判定为滑动事件
        } else {
          return ""
        }
      }
    },
    middleTouchEnd() {
      if (!this.touch.moved) {
        return
      }
      if (this.touch.toChange === "OK") {
        this.$refs.lyricList.$el.style.transform = `translate3d(0px,0,0)`
        this.currentShow = "lyric"
      } else {
        this.$refs.lyricList.$el.style.transform = `translate3d(375px,0,0)`
        this.currentShow = "cd"
      }
    },
    ...mapMutations({
      setFullScreen: "SET_FULL_SCREEN", // 设置播放页显示
      setPlayingState: "SET_PLAYING_STATE", // 设置播放状态
      setCurrentIndex: "SET_CURRENT_INDEX", // 设置索引，引起当前播放歌曲变化
      setVkey: "SET_VKEY",
      setPlayMode: "SET_PLAY_MODE",
      setPlayList: "SET_PLAYLIST"
    }),
    ...mapActions(["savePlayHistory", "saveFavoriteList", "deleteFavoriteList"])
  },
  watch: {
    vkey: function(val, oldVal) {
      this.songUrlData = songUrl(val, this.currentSong.mid)
      this.songPlay()
    },
    // 检测当前播放歌曲变化
    currentSong(newSong, oldSong) {
      if (!newSong.id) {
        return // 当清空播放列表时，newSong为空，则直接跳过下面操作
      }
      if (newSong === oldSong) {
        return // 当currentSong播放列表因为点击播放方式改变时，不做操作
      }
      // 清除当前歌词自动跳转计时
      if (this.currentLyric) {
        this.currentLyric.stop()
      }
      this.$nextTick(() => {
        this._getVkey(this.currentSong.mid)
      })
    },
    // 检测播放状态
    playing(val) {
      this.$nextTick(() => {
        const audio = this.$refs.audio
        val ? audio.play() : audio.pause()
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/assets/css/mixin.scss";
/* 背景图 */
.normal-player {
  background: rgb(34, 34, 34);
  color: #fff;
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  z-index: 400;
}
.normal-player .normal-bg {
  opacity: 0.6;
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  z-index: -1;
  filter: blur(20px);
}
.normal-player .normal-bg img {
  width: 100%;
  height: 100%;
}

/* 头部部分 */
.normal-player .header {
  width: 100%;
  background-size: 100% auto;
  position: relative;
  transition: all 0.4s cubic-bezier(0.86, 0.18, 0.82, 1.32);
}
.normal-player .header img {
  width: rem(32);
  height: rem(32);
  position: absolute;
  top: rem(7);
  left: rem(15);
}
.normal-player .header h1 {
  width: 70%;
  height: rem(45);
  margin: auto;
  overflow: hidden;
  text-align: center;
  line-height: rem(45);
  font-size: rem(16);
}
.normal-player .title-singer {
  width: 60%;
  height: rem(35);
  margin-left: auto;
  margin-right: auto;
  /* margin-bottom: rem(25); */
  overflow: hidden;
  font-size: rem(15);
  text-align: center;
}
/* 音量控制部分 */
.normal-player .volume {
  width: 100%;
  height: rem(30);
  margin-bottom: rem(15);
  position: relative;
}
.normal-player .volume img {
  display: inline-block;
  height: rem(20);
  margin-top: rem(5);
  position: absolute;
  top: 0;
  left: 8%;
}
.normal-player .volume .volume-control {
  width: 78%;
  position: absolute;
  left: 15%;
  top: 0;
}

/* 旋转大头像 */
.normal-player .middle {
  width: 100%;
  height: 64%;
  text-align: center;
  overflow: hidden;
  position: relative;
}
.middle img {
  width: rem(300);
  height: rem(300);
  border-radius: rem(300);
  border: rem(10) solid hsla(0, 0%, 100%, 0.1);
  opacity: 1;
  transition: all 0.5s;
}

/* 歌词部分 */
.lyric-wrapper {
  width: 80%;
  margin: 0 auto;
  overflow: hidden;
  text-align: center;
}
.text {
  overflow: hidden;
  line-height: rem(32);
  color: hsla(0, 0%, 100%, 0.5);
  font-size: rem(14);
}
.current {
  color: #fff;
  font-size: rem(16);
}
.middle-r {
  width: 100%;
  height: 64%;
  float: left;
  transform: translate3d(rem(375), 0, 0);
  position: absolute;
  top: 0;
}
.middleTime {
  transition: transform 0.5s;
}

/* 歌词轮播 */
.normal-player .dot-wrapper {
  width: 100%;
  height: rem(8);
  text-align: center;
  position: fixed;
  bottom: 22%;
}
.dot {
  display: inline-block;
  width: rem(8);
  height: rem(8);
  border-radius: rem(8);
  background: hsla(0, 0%, 100%, 0.5);
  transition: all 0.5s;
}
.active {
  width: rem(20);
  transition: all 0.5s;
  background: hsla(0, 0%, 100%, 0.8);
}

/* 播放进度条 */
.normal-player .time-box {
  width: 100%;
  height: rem(30);
  margin: auto;
  padding: rem(10) 0;
  position: fixed;
  bottom: 12%;
}
.normal-player .time-box .time {
  display: flex;
  width: rem(300);
  height: rem(30);
  margin: auto;
  justify-content: space-between;
}
.time span {
  display: inline-block;
  width: rem(30);
  height: rem(30);
  line-height: rem(30);
  font-size: rem(12);
}
.time span.time-l {
  padding-right: rem(10);
}
.time span.time-r {
  padding-left: rem(10);
}

/* 底部按钮控制栏 */
.normal-player .bottom-button-box {
  display: flex;
  width: 100%;
  height: rem(40);
  justify-content: space-between;
  padding: 0 rem(38);
  box-sizing: border-box;
  transition: all 0.4s cubic-bezier(0.86, 0.18, 0.82, 1.32);
  position: absolute;
  bottom: 7%;
}
.normal-player .bottom-button-box img {
  width: rem(40);
  height: rem(40);
}

/* 迷你音乐播放器 */
.mini-player {
  display: flex;
  width: 100%;
  height: rem(60);
  background: rgb(51, 51, 51);
  padding: rem(10);
  box-sizing: border-box;
  align-items: center;
  position: fixed;
  left: 0;
  bottom: 0;
  z-index: 410;
}
.mini-player .mini-player-con {
  width: 100%;
  height: rem(40);
}
.mini-player-con img {
  width: rem(40);
  height: rem(40);
  border-radius: rem(40);
}
.mini-player-con p {
  display: inline-block;
  max-width: rem(170);
  height: rem(40);
  overflow: hidden;
}
.mini-player-con p span {
  display: block;
  height: rem(20);
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  line-height: rem(20);
}
.mini-player-con p span.mini-title {
  color: #fff;
  font-size: rem(14);
}
.mini-player-con p span.mini-name {
  color: rgba(255, 255, 255, 0.3);
  font-size: rem(12);
}
.mini-player-con .playButton-box {
  width: rem(120);
  height: rem(40);
  float: right;
  box-sizing: border-box;
}
.playButton-box span{
	display: inline-block;
  width: rem(32);
	height: 100%;
  padding: rem(4) 0;
}
.playButton-box span img {
	width: rem(32);
  height: rem(32);
}

/* 动画 */
.normal-enter-active,
.normal-leave-active {
  transition: all 0.4s;
}
.normal-enter {
  opacity: 0;
  position: fixed;
  top: 0;
  left: 0;
}
.normal-leave-to {
  opacity: 0;
  top: 100%;
  left: -150%;
}

/* 唱片旋转 */
@keyframes rotate {
  0% {
    transform: rotate(0);
  }
  0% {
    transform: rotate(360deg);
  }
}
.playSrart {
  animation: rotate 20s linear infinite;
}
.playStorp {
  animation: rotate 20s linear infinite;
  /* -webkit-animation-play-state: paused; */
}

/* 滑动到歌词界面隐藏旋转头像 */
.middle .playImg {
  opacity: 0;
  transition: all 0.5s;
}
.cd-lyric {
  width: 80%;
  margin: 0 auto;
  height: rem(40);
  margin-top: 5%;
  overflow: hidden;
  text-align: center;
  color: hsla(0, 0%, 100%, 0.8);
  font-size: rem(16);
  line-height: rem(32);
}
</style>